package com.sllp.C71S3TsllpShop.web.back;

import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.sllp.C71S3TsllpShop.bean.Admin;
import com.sllp.C71S3TsllpShop.bean.Business;
import com.sllp.C71S3TsllpShop.bean.Result;
import com.sllp.C71S3TsllpShop.bean.User;
import com.sllp.C71S3TsllpShop.bean.VerifyCode;
import com.sllp.C71S3TsllpShop.biz.impl.AdminBizImpl;
import com.sllp.C71S3TsllpShop.biz.impl.BusinessBizImpl;
import com.sllp.C71S3TsllpShop.biz.impl.UserBizImpl;
import com.sllp.C71S3TsllpShop.util.AddCookie;
import com.sllp.C71S3TsllpShop.util.RandomUtils;
import com.sllp.C71S3TsllpShop.util.SendEmail;
import com.sllp.C71S3TsllpShop.util.VerificationCodeGeneratorUtil;

@Controller
@SessionAttributes({"backLoginBusiness","loginUser","backLoginAdmin","backResetPwdEmailCode"})
public class BackLoginAction {
	
	@Resource
	private BusinessBizImpl bbi;
	@Resource
	private AdminBizImpl abi;
	@Resource
	private UserBizImpl ub;
	@Resource
	private AddCookie addCookie;
	@Resource
	private SendEmail sendEmail;

	@GetMapping("back/toLogin.do")
	public String toLogin(HttpServletRequest request,HttpServletResponse response) {
		int landed = 0;
		Cookie[] cookies = request.getCookies();
		if(cookies!=null) {
			for (Cookie cookie : cookies) {
				if(cookie.getName().equals("backName")) {
					landed++;
					continue;
				}else if(cookie.getName().equals("backPwd")) {
					landed++;
					continue;
				}
			}
		} 
		if(landed == 0 || landed % 2 != 0 ) {
			Cookie cname = new Cookie("backName","" );
		    Cookie cpwd = new Cookie("backPwd", "");
		    response.addCookie(cname);
		    response.addCookie(cpwd);
		}
		return "back/login";
	}
	
	/**
	 * 管理员/用户登录
	 * @param user 用户名/密码
	 * @param backUserVerifyCode 输入的验证码
	 * @param remPwd  是否记住密码
	 * @param isAdmin 是否是管理员
	 * @param backVerifyCode 后端生成的验证码
	 * @param m
	 * @return
	 */
	@ResponseBody
	@PostMapping("back/loginNow.do")
	public Result loginNow(User user,String backUserVerifyCode,boolean remPwd,boolean isAdmin,
			@SessionAttribute("backVerifyCode") String backVerifyCode,Model m,
			HttpServletRequest request,HttpServletResponse response) {
		if(!backVerifyCode.equals(backUserVerifyCode)) {
			return new Result(0, "验证码错误");
		}
		if(isAdmin) {
			// 管理员登录
			Admin admin = new Admin();
			admin.setLoginName(user.getLoginName());
			admin.setPwd(user.getPwd());
			Result resultAdmin = abi.adminLogin(admin);
			if(resultAdmin.getSucess()==0) {
				return resultAdmin;
			}
			Admin loginAdmin = (Admin)resultAdmin.getObj();
			// 添加Cookie
			addCookie.addCookie(true, remPwd, loginAdmin.getLoginName(), loginAdmin.getPwd(), request, response);
			m.addAttribute("backLoginAdmin", resultAdmin.getObj());
			return new Result(resultAdmin.getSucess(), resultAdmin.getMessage());
		}else {
			// 商家登录
			Result resultBusinessUser = bbi.businessLogin(user);
			if(resultBusinessUser.getSucess()==0) {
				return resultBusinessUser;
			}
			@SuppressWarnings("unchecked")
			List<Object> objs=(List<Object>) resultBusinessUser.getObj();
			Business loginBusiness = (Business)objs.get(0);
			User loginUser = (User)objs.get(1);
			// 添加Cookie
			addCookie.addCookie(true, remPwd, loginUser.getLoginName(), loginUser.getPwd(), request, response);
			m.addAttribute("backLoginBusiness", loginBusiness);
			m.addAttribute("loginUser", loginUser);
			return new Result(resultBusinessUser.getSucess(), resultBusinessUser.getMessage());
		}
	}
	
	@GetMapping("back/logVerifyCode.do")
	public void toLogVerifyCode(HttpServletRequest request, HttpServletResponse response) {
		VerificationCodeGeneratorUtil iVerifyCodeGen = new VerificationCodeGeneratorUtil();
        try {
            //设置长宽
            VerifyCode verifyCode = iVerifyCodeGen.generate(80, 28);
            String code = verifyCode.getCode();
            //将VerifyCode绑定session
            request.getSession().setAttribute("backVerifyCode", code);
            //设置响应头
            response.setHeader("Pragma", "no-cache");
            //设置响应头
            response.setHeader("Cache-Control", "no-cache");
            //在代理服务器端防止缓冲
            response.setDateHeader("Expires", 0);
            //设置响应内容类型
            response.setContentType("image/jpeg");
            response.getOutputStream().write(verifyCode.getImgBytes());
            response.getOutputStream().flush();
        } catch (IOException e) {
        	System.out.println(e.getMessage());
        }
	}
	
	@Value("${mail.formMail.addr}")
	private String from;
	@Value("${mail.formMail.resetPwdEmailContent}")
	private String resetPwdEmailContent;
	
	@ResponseBody
	@PostMapping("back/sendBackResetPwdEmail.do")
	public Result sendBackResetPwdEmail(String userName,boolean resetIsAdmin,Model m) {
		if(resetIsAdmin) {
			Result result = abi.selectAdminByLoginName(userName);
			if(result.getSucess() == 0) {
				return result;
			}
			Admin admin = (Admin)result.getObj();
			// 生成验证码
			String resetPwdEmailCode = RandomUtils.randomString(4);
			// 将验证码放到session中
			m.addAttribute("backResetPwdEmailCode", resetPwdEmailCode);
			Result resultSendEmail = sendEmail.sendEmail("尤洪商城", from, admin.getEmail(), resetPwdEmailContent, resetPwdEmailCode,"请妥善保管验证码。");
			return resultSendEmail;
		}else {
			Result result = bbi.selectBusinessToSendEmailByLoginName(userName);
			if(result.getSucess() == 0) {
				return result;
			}
			User user = (User)result.getObj();
			// 生成验证码
			String resetPwdEmailCode = RandomUtils.randomString(4);
			// 将验证码放到session中
			m.addAttribute("backResetPwdEmailCode", resetPwdEmailCode);
			Result resultSendEmail = sendEmail.sendEmail("尤洪商城", from, user.getEmail(), resetPwdEmailContent, resetPwdEmailCode);
			return resultSendEmail;
		}
	}
	
	@ResponseBody
	@PostMapping("back/backResetPwd.do")
	public Result backResetPwd(String loginName,boolean isAdmin,
			String backResetPwdEmail,String resetPwd,
			@SessionAttribute("backResetPwdEmailCode") String backResetPwdEmailCode) {
		if(!backResetPwdEmail.equals(backResetPwdEmailCode)) {
			return new Result(0,"验证码错误");
		}
		if(isAdmin) {
			Admin admin = new Admin();
			admin.setLoginName(loginName);
			admin.setPwd(resetPwd);
			Result result = abi.resetAdminPwd(admin);
			return result;
		}else {
			User user = new User();
			user.setLoginName(loginName);
			user.setPwd(resetPwd);
			Result result = ub.updateUserPwd(user);
			return result;
		}
	}
}
